<?php

namespace app\modules\backend\controllers;

use app\models\Base;
use app\models\User;
use app\models\FeedBack;
use app\tools\Re;
use Yii;
use yii\helpers\Json;

class FeedBackController extends BaseController
{
    /**
     * @param string $type
     * @return array
     */
    public function actionList(){
        $page = Yii::$app->request->post('page', 0);
        $phone = Yii::$app->request->post('phone', '');
        $content = Yii::$app->request->post('content', '');
        $query = FeedBack::find()
          ->leftJoin('user', 'feed_back.user_id=user.id')
          ->where(['feed_back.status' => 1]);
        if ($phone) {
            $query->andWhere(['like', 'phone', $phone]);
        }
        if ($content) {
            $query->andWhere(['like', 'content', $content]);
        }
        $list = $query->orderBy("created_at desc")->limit(FeedBack::PAGE_SIZE)->offset(FeedBack::PAGE_SIZE*$page)->all();
        $feed_back_data = [];
        if ($list) {
            foreach ($list as $v) {
                $img = '';
                if ($v->imgs) {
                  $img_arr = explode(',', $v->imgs);
                  $img = $img_arr[0];
                }
                $img_ = $v->imgs ?  : '';
                $feed_back_data[] = [
                    'id' => $v->id,
                    'phone' => $v->user->phone,
                    'address' => $v->address,
                    'content' => $v->content,
                    'img' => $img,
                    'created_time' => date("Y-m-d H:i", $v->created_at),
                ];
            }
        }
        return Re::data([
            'data' => $feed_back_data,
            'totalPage' => $query->count(),
            'currentPage' => $page,
            'perPage' => FeedBack::PAGE_SIZE
        ]);
    }

    public function actionChangeFeedStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $feedInfo = FeedBack::findOne($id);
        if (empty($feedInfo)) {
            return Re::data(null, '反馈息读取失败', Re::ERROR);
        }
        $feedInfo->status = $status;
        $feedInfo->save();
        return Re::data();
    }
}
